package com.zyc.fuckfx;

import com.zyc.fuckfx.apk.ApkFileUtil;
import com.zyc.fuckfx.apk.ApkInfo;
import com.zyc.fuckfx.apk.ApkUtil;
import com.zyc.fuckfx.apk.HashUtil;
import com.zyc.fuckfx.base.ColorUtils;
import com.zyc.fuckfx.base.ImageUtils;
import com.zyc.fuckfx.base.Log;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Orientation;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.ImageView;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import org.apache.commons.codec.digest.MessageDigestAlgorithms;


import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;


import static com.zyc.fuckfx.apk.ApkFileUtil.*;

/**
 * @Author AlbertZyc
 * @Date 2022/8/13
 * @description 自己悟出来
 */
public class MainController implements Initializable {
    @FXML
    private Rectangle rectInputApk;

    @FXML
    private ScrollPane scRoot;

    @FXML
    private VBox vbContainer;

    @FXML
    private Label tvInputApk;

    @FXML
    private ImageView ivAppIcon;

    @FXML
    private Text tvAppName;

    @FXML
    private ListView<String> lvInfo;

    /**
     * 在窗体构建后，调用该方法
     */
    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        vbContainer.setBackground(ColorUtils.getBackground("#FAF9FF"));
        scRoot.setBackground(ColorUtils.getBackground("#FAF9FF"));
        ivAppIcon.setImage(ImageUtils.getResImage("icon_fucking_coka.png"));
        initApkDragAction();
    }

    private void initApkDragAction() {
        tvInputApk.setOnDragOver(event -> {
            if (event.getGestureSource() != tvInputApk && event.getDragboard().hasFiles()) {
                changeDragStatus(false);
                event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
            } else {
                changeDragStatus(true);

            }
            event.consume();
        });
        tvInputApk.setOnDragEntered(dragEvent -> Log.i("event setOnDragEntered"));
        tvInputApk.setOnDragExited(dragEvent -> {
            if (!dragEvent.isDropCompleted()) {
                changeDragStatus(true);
            }
        });
        tvInputApk.setOnDragDropped(event -> {
            Dragboard db = event.getDragboard();
            boolean success = false;
            if (db.hasFiles()) {
//                uploadFileEntry.setText(db.getFiles().toString());
                try {
                    fuckInfo(db.getFiles().get(0));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                success = true;
                changeDragStatus(true);
            }
            event.setDropCompleted(success);
            event.consume();
        });
    }

    private void changeDragStatus(boolean isFinish) {
        if (isFinish) {
            tvInputApk.setText("拖动APK到此处");
            rectInputApk.setFill(ColorUtils.getColor("#FFFFFF"));
        } else {
            tvInputApk.setText("松开鼠标！");
            rectInputApk.setFill(ColorUtils.getColor("#ECD2AA"));
        }
    }

    private void fuckInfo(File file) throws Exception {

        ApkUtil apkUtil = new ApkUtil();
        ApkInfo apkInfo = apkUtil.getApkInfo(file.getPath());


        tvAppName.setText(apkInfo.getAppName());
        //挪动APP——ICON到临时文件
        String iconPath = ApkFileUtil.getZipFilePath(APP_ICON_NAME);
        ApkFileUtil.extractFileFromApk(file.getPath(), apkInfo.getAppIcon(), iconPath);
        ivAppIcon.setImage(ImageUtils.getFileImage(iconPath));

        StringBuilder channel = new StringBuilder();
        try {
            //挪动APP——Channel到临时文件
            String channelPath = ApkFileUtil.getZipFilePath(APP_CHANNEL_NAME);
            ApkFileUtil.extractFileFromApk(file.getPath(), apkInfo.getChannelPath(), channelPath);
            for (String s : apkUtil.readFileLine(channelPath)) {
                channel.append(s).append(" ");
            }
        } catch (Exception e) {
            channel.append("没有读取到渠道文件");
        }


        ObservableList<String> items = FXCollections.observableArrayList(
                replenishString("APP名", apkInfo.getAppName()),
                replenishString("包名", apkInfo.getPackageName()),
                replenishString("版本号", apkInfo.getVersionCode()),
                replenishString("版本名", apkInfo.getVersionName()),
                replenishString("MD5", apkInfo.getMd5()),
                replenishString("SHA_1", apkInfo.getSha1()),
                replenishString("SHA_256", apkInfo.getSha256()),
                replenishString("渠道", channel.toString())
        );
        lvInfo.setPrefHeight(items.size() * 45);
        lvInfo.setCellFactory(param -> new InfoCellController());
        lvInfo.setOrientation(Orientation.VERTICAL);
        lvInfo.setItems(items);

//        String dexPath = ApkFileUtil.getZipFilePath(APP_CLASSES_NAME);
//        ApkFileUtil.extractFileFromApk(file.getPath(), "classes.dex", dexPath);
//        HashUtil.apkVerifyWithSHA(dexPath,"");
//        ApkSignerTool.main( new ArrayList<String>());

    }

    public String replenishString(String key, String value) {
        return key + "," + value;
    }

}